/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bff.gaia.examples.java.graph.util;

import com.bff.gaia.api.common.functions.FlatJoinFunction;
import com.bff.gaia.api.common.functions.FlatMapFunction;
import com.bff.gaia.api.common.functions.JoinFunction;
import com.bff.gaia.api.common.functions.MapFunction;
import com.bff.gaia.api.common.restartstrategy.RestartStrategies;
import com.bff.gaia.api.common.time.Time;
import com.bff.gaia.api.java.DataSet;
import com.bff.gaia.api.java.ExecutionEnvironment;
import com.bff.gaia.api.java.aggregation.Aggregations;
import com.bff.gaia.api.java.functions.FunctionAnnotation;
import com.bff.gaia.api.java.operators.DeltaIteration;
import com.bff.gaia.api.java.tuple.Tuple1;
import com.bff.gaia.api.java.tuple.Tuple2;
import com.bff.gaia.api.java.utils.ParameterTool;
import com.bff.gaia.configuration.Configuration;
import com.bff.gaia.core.AbstractCompensationFunc;
import com.bff.gaia.core.fs.FileSystem;
import com.bff.gaia.core.fs.Path;
import com.bff.gaia.examples.java.graph.ConnectedComponents;
import com.bff.gaia.util.Collector;

import java.net.URI;
import java.util.concurrent.TimeUnit;

public class ConnectedComponentsCompensationFunc extends AbstractCompensationFunc {
	private ParameterTool params;
	public ConnectedComponentsCompensationFunc(String args[]) {
		super(args);
		params = ParameterTool.fromArgs(args);
	}

	public String getpath() {                                  //提供一个接口，方便提供后面中间数据存储的路径
		if(params.has("path")){
			return params.get("path");
		}
		else return new String("file:///D://test/");
	}
	public void compensate() throws Exception {


		if(params.has("output")){
			String path = params.get("output");
			FileSystem fileSystem  = FileSystem.get(new URI(path));
			fileSystem.delete(new Path(path),true);
		}

		// Checking input parameters
		// set up execution environment
		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

		final int maxIterations = params.getInt("maxIterations", 1000);

		// make parameters available in the web interface
		env.getConfig().setGlobalJobParameters(params);
		env.setParallelism(20);
		env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, Time.of(5, TimeUnit.SECONDS)));

		// read vertex and edge data
		DataSet<Long> vertices = getVertexDataSet(env, params);
		DataSet<Tuple2<Long, Long>> edges = getEdgeDataSet(env, params).flatMap(new UndirectEdge());

		// assign the initial components (equal to the vertex id)

		DataSet<Tuple2<Long, Long>> verticesWithInitialId=vertices.map(new DuplicateValue<Long>());

		if(params.has("compensationDataPath")) {

			verticesWithInitialId = verticesWithInitialId.leftOuterJoin(readtempdata(env,params)).where(0).equalTo(0).with(
				new JoinFunction<Tuple2<Long, Long>, Tuple2<Long, Long>, Tuple2<Long, Long>>() {
					@Override
					public Tuple2<Long, Long> join(Tuple2<Long, Long> first, Tuple2<Long, Long> second) throws Exception {
						if(second!=null){
							return second;
						} else {
							return first;
						}
					}
				}
			);
		}

		// open a delta iteration
		DeltaIteration<Tuple2<Long, Long>, Tuple2<Long, Long>> iteration =
			verticesWithInitialId.iterateDelta(verticesWithInitialId, maxIterations, 0);

		// apply the step logic: join with the edges, select the minimum neighbor, update if the component of the candidate is smaller
		DataSet<Tuple2<Long, Long>> changes = iteration.getWorkset().join(edges).where(0).equalTo(0).with(new ConnectedComponents.NeighborWithComponentIDJoin())
			.groupBy(0).aggregate(Aggregations.MIN, 1)
			.join(iteration.getSolutionSet()).where(0).equalTo(0)
			.with(new ConnectedComponents.ComponentIdFilter());

		// close the delta iteration (delta and new workset are identical)
		DataSet<Tuple2<Long, Long>> result = iteration.closeWith(changes, changes);

		// emit result
		if (params.has("output")) {
			result.writeAsCsv(params.get("output"), "\n", ",", FileSystem.WriteMode.OVERWRITE);
			// execute program
			env.execute("Connected Components Example Recovery");
		} else {
			System.out.println("Printing result to stdout. Use --output to specify output path.");
			result.print();
		}
	}

	public static final class DuplicateValue<T> implements MapFunction<T, Tuple2<T, T>> {

		@Override
		public Tuple2<T, T> map(T vertex) {
			return new Tuple2<T, T>(vertex, vertex);
		}
	}

	/**
	 * Undirected edges by emitting for each input edge the input edges itself and an inverted version.
	 */
	public static final class UndirectEdge implements FlatMapFunction<Tuple2<Long, Long>, Tuple2<Long, Long>> {
		Tuple2<Long, Long> invertedEdge = new Tuple2<Long, Long>();

		@Override
		public void flatMap(Tuple2<Long, Long> edge, Collector<Tuple2<Long, Long>> out) {
			invertedEdge.f0 = edge.f1;
			invertedEdge.f1 = edge.f0;
			out.collect(edge);
			out.collect(invertedEdge);
		}
	}

	/**
	 * UDF that joins a (Vertex-ID, Component-ID) pair that represents the current component that
	 * a vertex is associated with, with a (Source-Vertex-ID, Target-VertexID) edge. The function
	 * produces a (Target-vertex-ID, Component-ID) pair.
	 */
	@FunctionAnnotation.ForwardedFieldsFirst("f1->f1")
	@FunctionAnnotation.ForwardedFieldsSecond("f1->f0")
	public static final class NeighborWithComponentIDJoin implements JoinFunction<Tuple2<Long, Long>, Tuple2<Long, Long>, Tuple2<Long, Long>> {

		@Override
		public Tuple2<Long, Long> join(Tuple2<Long, Long> vertexWithComponent, Tuple2<Long, Long> edge) {
			return new Tuple2<Long, Long>(edge.f1, vertexWithComponent.f1);
		}
	}

	/**
	 * Emit the candidate (Vertex-ID, Component-ID) pair if and only if the
	 * candidate component ID is less than the vertex's current component ID.
	 */
	@FunctionAnnotation.ForwardedFieldsFirst("*")
	public static final class ComponentIdFilter implements FlatJoinFunction<Tuple2<Long, Long>, Tuple2<Long, Long>, Tuple2<Long, Long>> {

		@Override
		public void join(Tuple2<Long, Long> candidate, Tuple2<Long, Long> old, Collector<Tuple2<Long, Long>> out) {
			if (candidate.f1 < old.f1) {
				out.collect(candidate);
			}
		}
	}

	// *************************************************************************
	//     UTIL METHODS
	// *************************************************************************

	private static DataSet<Long> getVertexDataSet(ExecutionEnvironment env, ParameterTool params) {
		if (params.has("vertices")) {
			return env.readCsvFile(params.get("vertices")).types(Long.class).map(
				new MapFunction<Tuple1<Long>, Long>() {
					public Long map(Tuple1<Long> value) {
						return value.f0;
					}
				});
		} else {
			return ConnectedComponentsData.getDefaultVertexDataSet(env);
		}
	}

	private static DataSet<Tuple2<Long, Long>> getEdgeDataSet(ExecutionEnvironment env, ParameterTool params) {
		if (params.has("edges")) {
			return env.readCsvFile(params.get("edges")).fieldDelimiter(",").types(Long.class, Long.class);
		} else {
			return ConnectedComponentsData.getDefaultEdgeDataSet(env);
		}
	}

	private static DataSet<Tuple2<Long,Long>> readtempdata(ExecutionEnvironment env, ParameterTool params)
	{
		Configuration parameters = new Configuration();
		parameters.setBoolean("recursive.file.enumeration", true);
		return env.readTextFile(params.get("compensationDataPath")).withParameters(parameters).map(new MapFunction<String, Tuple2<Long,Long>>() {
			public Tuple2<Long,Long> map(String s){
				String [] a = s.split(",");
				Long x = Long.parseLong(a[0].substring(1,a[0].length()));
				Long y = Long.parseLong(a[1].substring(0,a[1].length()-1));
				return new Tuple2<Long,Long>(x,y);
			}
		});
	}
}